package com.example.controller;

import com.example.common.Result;
import com.example.entity.Clock;
import com.example.entity.GridReservation;
import com.example.service.ClockService;
import com.example.service.GridReservationService;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 打卡的控制层
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("/clock")
public class ClockController {

    private final ClockService clockService;
    private final GridReservationService gridReservationService;

    /**
     * 增
     **/
    @PostMapping("/add")
    public Result add() {
        GridReservation gridReservation = new GridReservation();
        gridReservation.setUserId(TokenUtils.getCurrentUser().getId());
        gridReservation.setTime(LocalDate.now());
        if (gridReservationService.selectAll(gridReservation).isEmpty())
            return Result.error("400", "今日无预约");
        Clock clock = new Clock();
        clock.setUserId(TokenUtils.getCurrentUser().getId());
        clock.setTime(LocalDate.now());
        if (!clockService.selectAll(clock).isEmpty())
            return Result.error("400", "勿重复打卡");
        clockService.add(clock);
        return Result.success();
    }

    /**
     * 删
     **/
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        clockService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     **/
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        clockService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 改
     **/
    @PutMapping("/update")
    public Result updateById(@RequestBody Clock clock) {
        clockService.updateById(clock);
        return Result.success();
    }

    /**
     * 根据ID查询
     **/
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Clock clock = clockService.selectById(id);
        return Result.success(clock);
    }

    /**
     * 查询所有
     **/
    @GetMapping("/selectAll")
    public Result selectAll(Clock clock) {
        List<Clock> list = clockService.selectAll(clock);
        return Result.success(list);
    }

    /**
     * 分页查询
     **/
    @GetMapping("/selectPage")
    public Result selectPage(Clock clock,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Clock> page = clockService.selectPage(clock, pageNum, pageSize);
        return Result.success(page);
    }

    @GetMapping("/rank")
    public Result rank() {
        return Result.success(clockService.selectRank());
    }

}